package com.it.gw.modules.station.activity

import PictureVo
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.it.common.utils.DialogUtils
import com.it.common.utils.DisplayUtil
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.StringUtils
import com.it.common.utils.UriUtils
import com.it.common.utils.isNotEmpty
import com.it.data.network.req.PicDto
import com.it.data.network.req.UploadFileDto
import com.it.data.network.rsp.GQYWXXVo
import com.it.gw.BuildConfig
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityGqstationPicBinding
import com.it.gw.databinding.DialogSelectPicBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.modules.station.adapter.PicListAdapter
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date


//站点图片
class GQStationPicActivity : BaseActivity<ActivityGqstationPicBinding>() {
    private val dataList by lazy { mutableListOf<PictureVo>() }
    private val adapter by lazy {
        PicListAdapter(context = this, datas = dataList, listener = {
            addOrSeeView(it)
        }, delete = {
            it.filePath = null
            it.pic_Url = null
            refreshView()
        })
    }

    /**
     * 添加还是查看
     * @param vo PictureVo
     */
    private fun addOrSeeView(vo: PictureVo) {
        if (vo.pic_Url.isNullOrEmpty() && vo.filePath.isNullOrEmpty()) {
            showPicSelect(vo)
        } else {
            seePicView(vo)
        }
    }

    /**
     * 查看
     * @param vo PictureVo
     */
    private fun seePicView(vo: PictureVo) {
        val intent = Intent(this, PhotoViewActivity::class.java)
        intent.putExtra("url", vo.pic_Url)
        intent.putExtra("filePath", vo.filePath)
        startActivity(intent)

    }

    private lateinit var currentVo: PictureVo

    /**
     * 选择拍照或者相册
     * @param vo PictureVo
     */
    private fun showPicSelect(vo: PictureVo) {
        currentVo = vo
        val dialogSelectPicBinding = DialogSelectPicBinding.inflate(layoutInflater)
        val dialog =
            DialogUtils.getDialog(this, dialogSelectPicBinding.root)
        dialogSelectPicBinding.rlCancel.setOnClickListener {
            dialog.dismiss()
        }
        dialogSelectPicBinding.rlCamera.setOnClickListener {
            dialog.dismiss()
            takePhoto(takePhotoAction = {
                currentVo.filePath = it
                refreshView()
            })
        }
        dialogSelectPicBinding.rlPhoto.setOnClickListener {
            dialog.dismiss()
            pickMedia(pickMediaAction = {
                currentVo.filePath = it
                refreshView()
            })
        }

        dialog.show()

    }

    private fun refreshView() {
        adapter.notifyDataSetChanged()

    }

    companion object {
        const val TAG = "OperationRecordActivity"
    }

    var gqywxxVo: GQYWXXVo? = null
    override fun initObserver() {
        mainViewModel.gqywxxVoLiveData.observe(this) {
            ProgressDialog.hide()
            Log.d(
                TAG,
                "initObserver: gqywxxVoLiveData ${it.data?.rtuModel} -  ${it.data?.rtuModel == null} -${it.data?.rtuModel == "null"}"
            )
            gqywxxVo = it.data
            binding.STCD.text = StringUtils.getNoNullData(it.data?.stcd)
            binding.STNM.text = StringUtils.getNoNullData(it.data?.stnm)
            binding.STTP.text = StringUtils.getNoNullData("${it.data?.sttp}:${it.data?.sttpName}")


        }
        gqStationViewModel.pictureVoListLiveData.observe(this) {
            ProgressDialog.hide()
            dataList.clear()
            if (it.result && it.data.isNotEmpty()) {
                dataList.addAll(it.data!!)
            }
            else{
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_LONG).show()
            }


            refreshView()

        }

    }

    private fun getGQStationInfo() {
        val stcd = intent.getStringExtra("stcd")
        mainViewModel.getGQYWXX(STCD = stcd!!)
        gqStationViewModel.getGQPicByStcd(STCD = stcd)
    }

    override fun initListener() {
        binding.btnSave.setOnClickListener {
            ProgressDialog.show(this@GQStationPicActivity)
            lifecycleScope.launch {
                try {
                    val dto = PicDto(
                        stcd = gqywxxVo?.stcd,
                        stnm = gqywxxVo?.stnm,
                        lttdandlgtd = "00,00",
                    )
                    Log.d(TAG, "uploadPic: start ${dto} ")
                    val uploadFileDtoList = mutableListOf<UploadFileDto>()
                    dataList.forEach { v ->
                        uploadFileDtoList.add(
                            UploadFileDto(
                                file = if (v.filePath.isNotEmpty()) File(v.filePath) else null,
                                fileName = v.piccd
                            )
                        )
                    }
                    Log.d(TAG, "uploadPic: start ${uploadFileDtoList} ")
                    val res = gqStationViewModel.saveGQStcdPic(dto = dto, uploadFileDtoList)
                    ProgressDialog.hide()
                    if (res.success == true) {
                        Toast.makeText(this@GQStationPicActivity, "上传成功", Toast.LENGTH_SHORT)
                            .show()
                        isEdit = false
                        binding.tvEdit.text = "编辑"
                        getGQStationInfo()
                    } else {
                        Toast.makeText(this@GQStationPicActivity, "上传失败", Toast.LENGTH_SHORT)
                            .show()
                    }
                } catch (e: Exception) {
                    ProgressDialog.hide()
                    Log.d(TAG, "initListener: ${e}")
                    Toast.makeText(
                        this@GQStationPicActivity,
                        "上传失败,${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }


            }


        }

        binding.tvEdit.setOnClickListener {
            isEdit = !isEdit
            dataList.forEach {
                it.isEdit = isEdit
            }
            if (isEdit) {
                binding.tvEdit.text = "查看"
                refreshView()
            } else {
                binding.tvEdit.text = "编辑"
                dataList.clear()
                adapter.notifyDataSetChanged()
                getGQStationInfo()
            }


        }

    }


    override fun initData() {
        ProgressDialog.show(this)
        getGQStationInfo()
    }

    var isEdit = false
    override fun initView() {
        setTitle(
            title = R.string.str_gq_pic,
            isBack = true,

            )
        val map = hashMapOf(
            RvSpacesItemUtils.BOTTOM_DECORATION to DisplayUtil.dip2px(this, 15f),
            RvSpacesItemUtils.RIGHT_DECORATION to DisplayUtil.dip2px(this, 15f)
        )
        binding.rvList.addItemDecoration(RvSpacesItemUtils(map))
        binding.rvList.layoutManager = GridLayoutManager(this, 3)
        binding.rvList.adapter = adapter



    }


    override fun setContentView() {
        binding = ActivityGqstationPicBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }


}